<template>
  <view class="app-container order-list">
    <view class="search-main">
      <view class="p-20">
        <u-search
          v-model="query.search"
          height="30"
          :showAction="false"
          @search="handleSearch"
          @clear="handleSearch"
          placeholder="订单编号/商品名称"
        ></u-search>
      </view>
      <view style="padding: 0 20rpx">
        <u-tabs
          :list="tabList"
          v-model:current="current"
          lineColor="#5ae372"
        ></u-tabs>
      </view>
    </view>
    <view id="scrollWrapper" class="flex-1" style="overflow: hidden">
      <scroll-view
        scroll-y
        :style="{ height: scrollWrapperHeight + 'px' }"
        @scrolltolower="handleScrolltolower"
      >
        <view class="p-20" style="box-sizing: border-box">
          <view
            v-for="(item, index) in list"
            :key="index"
            @click="handleToDetail(item)"
          >
            <view class="my-card mb-20">
              <view class="flex justify-between items-center">
                <view>
                  <u-text
                    :text="item.merchant ? item.merchant.name : ''"
                    bold
                  ></u-text>
                </view>
                <view>
                  <u-text
                    :text="formatStatus(item.status)"
                    type="info"
                  ></u-text>
                </view>
              </view>
              <u-gap height="10"></u-gap>
              <view class="field">
                <view class="label">下单时间</view>
                <view class="value">{{ item.created_at }}</view>
              </view>
              <u-gap height="10"></u-gap>
              <view class="field">
                <view class="label">下单数量</view>
                <view class="value">{{ item.lines.length }}种</view>
              </view>
              <u-gap height="10"></u-gap>
              <view class="field">
                <view class="label">订单编号</view>
                <view class="value">
                  <u-text :lines="1" :text="item.code"></u-text>
                </view>
              </view>
              <u-gap height="10"></u-gap>
              <view v-if="item.lines.length" @click.stop>
                <u-album
                  :maxCount="3"
                  :singleSize="100"
                  :multipleSize="100"
                  lazy-load
                  :urls="[
                    ...item.lines.map((i) =>
                      i.product ? i.product.image_url : ''
                    ),
                  ]"
                ></u-album>
              </view>
              <u-gap height="10"></u-gap>
              <u-line height="1"></u-line>
              <u-gap height="10"></u-gap>
              <view class="field">
                <view class="label">订单金额</view>
                <view class="value flex-1 flex justify-between items-center">
                  <text style="font-weight: bold; color: #e54746"
                    >￥{{ item.total_price }}</text
                  >
                  <u-icon name="arrow-right"></u-icon>
                </view>
              </view>
            </view>
          </view>
        </view>
        <u-gap height="10"></u-gap>
        <u-text
          text="没有更多了"
          type="info"
          align="center"
          v-if="list.length > 0"
        ></u-text>
        <u-gap height="10"></u-gap>
        <my-empty type="order" v-if="list.length <= 0"></my-empty>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import { orderList } from "@/common/apis/order";
import { onReady, onShow } from "@dcloudio/uni-app";

// 定义一个响应式变量 scrollWrapperHeight，初始值为 600
const scrollWrapperHeight = ref(600);

// 定义一个响应式对象 query，包含订单状态、页码、每页数量和搜索关键词
const query = reactive({
  status: "",
  page: 1,
  size: 10,
  search: "",
});

// 定义一个响应式变量 current，初始值为 0
const current = ref(0);

// 定义一个响应式数组 tabList，包含订单状态的名称和值
const tabList = ref([
  { name: "全部", value: "all" },
  { name: "待支付", value: "pending" },
  { name: "已支付", value: "paid" },
  { name: "已发货", value: "express" },
  { name: "已完成", value: "completed" },
  { name: "已取消", value: "canceled" },
]);

// 定义一个响应式数组 list，初始值为空数组
const list = ref([]);

// 定义一个响应式变量 totalPage，初始值为 0
const totalPage = ref(0);

// 监听 current 的变化，当 current 变化时，更新 query 的 status 和 page，并调用 fetchOrderList 函数
watch(
  () => current.value,
  (val) => {
    const status = tabList.value[val].value;
    query.status = status == "all" ? "" : status;
    query.page = 1;
    fetchOrderList(true);
  }
);

// 定义一个函数 formatStatus，用于将订单状态的值转换为名称
const formatStatus = (status) => {
  return tabList.value.find((i) => i.value == status).name;
};

// 定义一个异步函数 fetchOrderList，用于获取订单列表
async function fetchOrderList(isCover = true) {
  const response = await orderList(query);
  if (response) {
    totalPage.value = response.total_page;
    if (isCover) {
      list.value = response.records;
    } else {
      list.value = list.value.concat(response.records);
    }
  }
  return response;
}

// 定义一个异步函数 handleScrolltolower，用于处理滚动到底部的事件
async function handleScrolltolower() {
  if (query.page < totalPage.value) {
    query.page += 1;
    await fetchOrderList(false);
  }
}

// 定义一个函数 handleSearch，用于处理搜索事件
function handleSearch() {
  query.page = 1;
  fetchOrderList();
}

// 定义一个函数 handleToDetail，用于处理点击订单详情的事件
function handleToDetail(i) {
  console.log(i);
  uni.$u.route({
    url: "/pages/order/detail",
    params: {
      id: i.id,
    },
  });
}

// 在页面显示时调用 fetchOrderList 函数
onShow(() => {
  fetchOrderList();
});

// 在页面准备好时，获取 scrollWrapper 的高度，并赋值给 scrollWrapperHeight
onReady(() => {
  const wrapper = uni.createSelectorQuery().select("#scrollWrapper");
  wrapper.boundingClientRect().exec((res) => {
    if (res[0]) {
      scrollWrapperHeight.value = res[0].height;
    }
  });
});
</script>

<style lang="scss" scoped>
.search-main {
  background-color: #ffffff;
}
.field {
  display: flex;

  .label {
    width: 6em;
    color: $u-info;
  }
}
</style>
